package BookManagement.dao;

import BookManagement.domain.Book;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;

@Repository
public interface BookDao {

    @Select("select * from book where bookISBN=#{bookISBN}")
    public Book findByISBN(String bookISBN);

    @Select("<script>"+"select * from book order by CONVERT(bookname USING gbk) ASC"+
            "<if test='start!=null and size!=null'>"+"limit #{start},#{size}"+"</if>"
            +"</script>"
    )
    public List<Book> findAllBooks(HashMap<String,Object> map);

    @Select("select count(*) from book")
    public int getTotalBooks();

    @Select("select count(*) from book where author like '%${value}%' or bookname like '%${value}%'")
    public int getTotalBooksBy(String str);


    @Select("<script>"+"select * from book"+
            " <where> "+ "<if test='str!=null'>"+" author like concat('%',#{str},'%') or bookName like concat('%',#{str},'%')"+"</if>"+" </where> "+
            " order by CONVERT(bookname USING gbk) ASC"+
            "<if test='start!=null and size!=null'>"+"limit #{start},#{size}"+"</if>"
            +"</script>"
    )
    public List<Book> findByBookNameOrAuthor(HashMap<String,Object> map);

    @Insert("insert into book values(#{bookISBN},#{bookName},#{bookCounts},#{bookPrices},#{detail},#{author},#{photo})")
    public int addBook(Book b);

    @Delete("delete from book where bookISBN=#{bookISBN}")
    public int deleteBookByISBN(String ISBN);

    @Update("<script>"+
            "update book"+"<set>"+
            "<if test='bookName!=null'>"+"bookName=#{bookName},"+"</if>"+
            "<if test='bookCounts!=null'>"+"bookCounts=#{bookCounts},"+"</if>"+
            "<if test='bookPrices!=null'>"+"bookPrices=#{bookPrices},"+"</if>"+
            "<if test='detail!=null'>"+"detail=#{detail},"+"</if>"+
            "<if test='author!=null'>"+"author=#{author},"+"</if>"+
            "<if test='photo!=null'>"+"photo=#{photo}"+"</if>"+
            "</set>"+"where bookISBN=#{bookISBN}"+"</script>"
    )
    public int updateBook(Book b);

    @Update("update book set bookCounts=#{bookCounts} where bookISBN=#{bookISBN}")
    public int updateBookCounts(HashMap<String,Object> map);
}
